//
//  FLGuideView.m
//  Follow
//
//  Created by liangshangjia on 16/5/9.
//  Copyright © 2016年 Sami-industry. All rights reserved.
//

#import "FLGuideView.h"
#import "FLGuidePageView.h"
#import "FLGuideIndicatorView.h"

typedef void (^complection)();

@interface FLGuideView () <UIScrollViewDelegate , FLGuidePageViewDelegate>
@property (nonatomic, assign) int page;
@end

@implementation FLGuideView {
    UIScrollView            *_scrollView;
    FLGuideIndicatorView    *_indicatorView;
    complection              _complectionBlock;
    UIButton                *_bottomButton;
}

+ (instancetype)customGuideView
{
    FLGuideView *guideView = [[FLGuideView alloc]initWithFrame:(CGRect){{0,0},kPageSize}];
    [guideView configure];

    return guideView;
}


- (void)configure
{

    UIImageView *imageView = [[UIImageView alloc]init];
    imageView.image = [self.class getTheLaunchImage];
    [self addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(@0);
    }];

    if (![[self class] needToIntroduce]) {
        return;
    }

    _scrollView                                 = [[UIScrollView alloc]initWithFrame:self.bounds];
    _scrollView.contentSize                     = CGSizeMake(kPageSize.width*kNumOfPage, 0);
    _scrollView.pagingEnabled                   = YES;
    _scrollView.showsHorizontalScrollIndicator  = NO;
    _scrollView.delegate                        = self;
    _scrollView.backgroundColor                 = HEXCOLOR(@"#FFE832");
    [self addSubview:_scrollView];
    
    for (NSInteger i = 0; i < kNumOfPage; i ++) {
        FLGuidePageView *page = [FLGuidePageView guidePageWithTopMargin_icon:SM_SIZE(236) andTopMargin_word:SM_SIZE(894) withPage:(int)i];
        [page setFrame:(CGRect){{ kPageSize.width*i ,0 }, kPageSize }];
        [page setTag:kFLGuideViewBaseTag + i];
        [page setDelegate:self];
        [_scrollView addSubview:page];
    }
    
    _indicatorView = [FLGuideIndicatorView indicatorViewWithNumOfPage:kNumOfPage];
    [self addSubview:_indicatorView];
    [_indicatorView setCurrentPage:0 animated:YES];
    [_indicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.mas_centerX);
        make.bottom.equalTo(@(-SM_SIZE(120)));
    }];

    //底部按钮
    _bottomButton = [UIButton new];
    [_bottomButton setBackgroundImage:[UIImage imageWithColor:SM_thumeColor] forState:UIControlStateNormal];
    [_bottomButton setTitle:@"开始买买买" forState:UIControlStateNormal];
    _bottomButton.titleLabel.font = SM_NBFont(34);
    [_bottomButton setTitleColor:SM_whiteColor forState:UIControlStateNormal];
    _bottomButton.layer.cornerRadius = SM_SIZE(45);
    _bottomButton.clipsToBounds = YES;
    [_bottomButton addTarget:self action:@selector(didClickBottomButton:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_bottomButton];


}

- (void)showInView:(UIView *)view withComplection:(void (^)(void))complection
{
    _complectionBlock = complection;
    [view addSubview:self];
    if (![[self class] needToIntroduce]) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self didClickBottomButton:nil];
        });
    }
}

- (void)callback
{
    if (_complectionBlock) {
        _complectionBlock();
    }
}


+ (BOOL)needToIntroduce { //判断是否需要显示app引导页
    // app版本
    NSString *app_Version = [[[NSBundle mainBundle] infoDictionary]objectForKey:@"CFBundleShortVersionString"];
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    BOOL isNew = ![[ud objectForKey:app_Version] integerValue]; //非第一次运行，不为非(!)
    return isNew;
}

- (void)writeAppVersion
{
    NSString *app_Version = [[[NSBundle mainBundle] infoDictionary]objectForKey:@"CFBundleShortVersionString"];
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setObject:@(1) forKey:app_Version];
    [ud synchronize];//立即同步
}


#pragma mark - scroll view
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    int index = round(scrollView.contentOffset.x/scrollView.width);

    if (_page == index) {
        return;
    }

    FLGuidePageView *lastPage = [scrollView viewWithTag:kFLGuideViewBaseTag + _page];
    [lastPage showAnimationWhenDidDisappear];

    _page = index;
    FLGuidePageView *page = [scrollView viewWithTag:kFLGuideViewBaseTag + _page];
    [page showAnimationWhenDidAppear];
    [_indicatorView setCurrentPage:_page animated:YES];

    [self checkPage];
}

BOOL isAnimatingShow = NO;
BOOL isAnimatingDismiss = NO;
- (void)checkPage
{
    if (_page == kNumOfPage - 1) {
        if (isAnimatingShow) {
            return;
        }
        isAnimatingDismiss = NO;
        _bottomButton.hidden = NO;
        _bottomButton.alpha = 1;
        _bottomButton.frame = [_indicatorView convertRect:_indicatorView.currentImageView.frame toView:self];
        [UIView animateWithDuration:.3 delay:.2 options:UIViewAnimationOptionCurveEaseInOut|UIViewAnimationOptionAllowUserInteraction animations:^{
            _bottomButton.frame = CGRectMake(SM_SIZE(200), 0, SM_SCREEN_WIDTH-SM_SIZE(200)*2, SM_SIZE(90));
            _bottomButton.center = CGPointMake(self.centerX, _indicatorView.centerY);
        } completion:^(BOOL finished) {
            isAnimatingShow = NO;
        }];

    }else {
        if (isAnimatingDismiss) {
            return;
        }
        [UIView animateWithDuration:.3 delay:.2 options:UIViewAnimationOptionCurveEaseInOut|UIViewAnimationOptionAllowUserInteraction animations:^{
            _bottomButton.frame = [_indicatorView convertRect:_indicatorView.currentImageView.frame toView:self];
        } completion:^(BOOL finished) {
            if (isAnimatingDismiss) {
                _bottomButton.alpha = 0;
                _bottomButton.hidden = YES;
                isAnimatingDismiss = NO;
            }
        }];
    }
}


#pragma mark - FLGuidePageViewDelegate
- (void)didClickBottomButton:(UIButton *)button
{
    [self callback];
    [UIView animateWithDuration:1 animations:^{
        self.alpha = 0.f;
        self.transform = CGAffineTransformMakeScale(1.2, 1.2);
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        if ([self.class needToIntroduce]) {
            [self writeAppVersion];
        }
    }];
    
}


+ (UIImage *)getTheLaunchImage
{
    NSString *defaultImageName = @"LaunchImage";
    NSInteger osVersion = floor([[[UIDevice currentDevice] systemVersion] floatValue])*100;

    NSInteger screenHeight = CGRectGetHeight([UIScreen mainScreen].bounds);
    // 3.5inch
    if (screenHeight < 568) {

        if (osVersion >= 700) {
            defaultImageName = [NSString stringWithFormat:@"%@-700",defaultImageName];
        } else {
            defaultImageName = [NSString stringWithFormat:@"%@",defaultImageName];
        }

    }
    // 4.0inch
    else if(screenHeight < 667){

        if (osVersion >= 700) {
            defaultImageName = [NSString stringWithFormat:@"%@-700-568h",defaultImageName];
        } else {
            defaultImageName = [NSString stringWithFormat:@"%@-568h",defaultImageName];
        }
    }
    // 4,7inch
    else if (screenHeight < 736) {

        defaultImageName = [NSString stringWithFormat:@"%@-800-667h",defaultImageName];

    }
    // 5.5inch
    else{
        NSString *orientation = @"";
        switch ([[UIApplication sharedApplication] statusBarOrientation]) {
            case UIInterfaceOrientationUnknown:
            case UIInterfaceOrientationPortrait:
            case UIInterfaceOrientationPortraitUpsideDown:
                orientation = @"Portrait";
                break;
            case UIInterfaceOrientationLandscapeLeft:
            case UIInterfaceOrientationLandscapeRight:
                orientation = @"Landscape";
                break;
            default:
                break;
        }
        defaultImageName = [NSString stringWithFormat:@"%@-800-%@-736h",defaultImageName,orientation];
    }
    return [UIImage imageNamed:defaultImageName];
}
@end
